<template>
  <div id="receiver">
    <h1>接收分数</h1>
    <div v-for="(message, index) in messages" :key="index">
      {{ message }}
    </div>
    <button @click="reconnect" v-if="!isConnected">重新连接</button>
    <p v-if="statusMessage" :class="{ 'success': isConnected, 'error': !isConnected }">{{ statusMessage }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: null,
      isConnected: false,
      statusMessage: '',
      messages: [],
      reconnectAttempts: 0,
      maxReconnectAttempts: 5,
      jwtToken: localStorage.getItem("user")
    };
  },
  methods: {
    // 初始化 WebSocket
    initWebSocket() {
      this.ws = new WebSocket("ws://localhost:8081/api/chat");

      this.ws.onopen = () => {
        console.log("WebSocket connection established");
        this.isConnected = true; // 设置连接标志位
        this.statusMessage = 'WebSocket连接已建立';
        this.reconnectAttempts = 0; // 重置重连次数
      };

      this.ws.onclose = (event) => {
        console.log("WebSocket connection closed", event);
        this.isConnected = false; // 清除连接标志位
        this.statusMessage = 'WebSocket连接已关闭';
      };

      this.ws.onerror = (error) => {
        console.error("WebSocket error:", error);
        this.isConnected = false; // 清除连接标志位
        this.statusMessage = 'WebSocket连接失败';
        this.reconnect(); // 自动重连
      };

      this.ws.onmessage = (message) => {
        console.log("Received message:", message.data);
        this.messages.push(message.data);
      };
    },
    // 重新连接 WebSocket
    reconnect() {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++;
        console.log(`Attempting to reconnect... Attempt ${this.reconnectAttempts}`);
        setTimeout(() => {
          this.initWebSocket();
        }, 2000); // 每次重连间隔2秒
      } else {
        console.error("Max reconnect attempts reached");
        this.statusMessage = '达到最大重连次数，连接失败';
      }
    }
  },
  mounted() {
    this.initWebSocket();
  }
};
</script>

<style scoped>
#receiver {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 50px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.success {
  color: green;
}

.error {
  color: red;
}
</style>